import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../../entities/user.entity';
import { Repository } from 'typeorm';
import { RegisterUserDto } from '../../dto/user/registerUser.dto';
import { EncryptService } from '../../common/service/encrypt.service';
import { CODE } from '../../common/enum/code.enum';
import { LoginUserDto } from '../../dto/user/loginUser.dto';
import { plainToClass } from 'class-transformer';
import { UserInfoDto } from '../../dto/user/userInfo.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private encryptService: EncryptService,
  ) {}

  findAll() {
    return this.userRepository.find();
  }

  findOne(id: string) {
    return this.userRepository.findOneBy({ id });
  }

  async register(registerUserDto: RegisterUserDto) {
    try {
      const user = this.userRepository.create(registerUserDto);
      user.password = await this.encryptService.encrypt(user.password);
      return await this.userRepository.save(user);
    } catch (e) {
      if (e.message.includes('UQ_ACCOUNT')) {
        return { code: CODE.HAS_ACCOUNT, message: '该账号已存在' };
      }
      if (e.message.includes('UQ_NAME')) {
        return { code: CODE.HAS_NAME, message: '该昵称已存在' };
      }
      return { code: CODE.SQL_ERROR, message: e.message };
    }
  }

  async login(loginUserDto: LoginUserDto) {
    let user: User;
    try {
      user = await this.userRepository.findOneBy({
        account: loginUserDto.account,
      });
    } catch (e) {
      return { code: CODE.SQL_ERROR, message: e.message };
    }

    if (!user) {
      return { code: CODE.NOT_ACCOUNT, message: '账号不存在' };
    } else {
      const res = await this.encryptService.compare(
        loginUserDto.password,
        user.password,
      );
      if (res) return plainToClass(UserInfoDto, user);
      else return { code: CODE.NOT_PASSWORD, message: '密码错误' };
    }
  }
}
